<template>
  <div class="app-container">
    <!-- 顶部功能 -->
    <div class="filter-container" style="margin-bottom: 15px">
      <!-- 试卷名 -->
      <el-input v-model="queryParam.name" placeholder="试卷名" style="width: 200px" class="filter-item"
        @keyup.enter.native="handleFilter" />
      <!-- 一些按钮 -->
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleShowAll">
        显示全部
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加试卷
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px" type="danger" icon="el-icon-delete"
        @click="handleDeleteSome">
        批量删除
      </el-button>
    </div>
    <!--弹出框-->
    <!-- :close-on-click-modal="false" -->
    <el-dialog :title="formTitle" :visible.sync="dialogFormVisible" width="40%">
      <el-row>
        <el-col :span="16">
          <!--普通表单-->
          <el-form ref="ruleForm" :model="form" :rules="rules" label-width="120px">
            <el-form-item label="题库名称" prop="repoId">
              <el-select v-model="form.repoId" placeholder="请选择" style="width: 100%;" :disabled="canDelete(form)">
                <el-option v-for="item in repoList" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="试卷名称" prop="name">
              <template>
                <el-input v-model="form.name" />
              </template>
            </el-form-item>
            <el-form-item label="单选题数量" prop="sigleCount">
              <el-input v-model.number="form.sigleCount" :disabled="canDelete(form)" />
            </el-form-item>
            <el-form-item label="多选题数量" prop="multiCount">
              <el-input v-model.number="form.multiCount" :disabled="canDelete(form)" />
            </el-form-item>
            <el-form-item label="判断题数量" prop="judgeCount">
              <el-input v-model.number="form.judgeCount" :disabled="canDelete(form)" />
            </el-form-item>
            <!-- <el-form-item label="总分" prop="totalScore">
              <el-input v-model="form.totalScore" :disabled="canDelete(form)" />
            </el-form-item> -->
            <el-form-item label="及格分" prop="qualifyScore">
              <el-input v-model="form.qualifyScore" :disabled="canDelete(form)" />
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    <!--数据表格-->
    <el-table ref="multipleTable" :data="tableData" border>
      <el-table-column fixed type="selection" width="55" align="center" :selectable="selectable" />

      <el-table-column prop="id" label="序号" align="center" width="100" />

      <el-table-column prop="name" label="试卷名" align="center">
        <template slot-scope="scope">
          <el-link type="primary" @click="handleUpdate(scope.row)">{{
        scope.row.name
      }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="questionCount" label="题目数量" align="center" />
      <el-table-column prop="sigleCount" label="单选题数量" align="center" />
      <el-table-column prop="multiCount" label="多选题数量" align="center" />
      <el-table-column prop="judgeCount" label="判断题数量" align="center" />
      <el-table-column prop="totalScore" label="总分" align="center" />

      <el-table-column prop="qualifyScore" label="及格分" align="center" />

      <el-table-column prop="createTime" label="创建时间" align="center" />

      <el-table-column prop="updateTime" label="更新时间" align="center" />

      <el-table-column fixed="right" label="操作" width="150" align="center">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button type="danger" :disabled="canDelete(scope.row)" size="small"
            @click="handleDelete(scope.row, scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页条-->
    <el-pagination background :current-page.sync="queryParam.pageNum" :page-sizes="[5, 10, 20, 50]"
      :page-size="queryParam.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="recordTotal"
      style="margin-top: 15px" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import {
  queryPapersByPage,
  removePaper,
  removePapers,
  updatePaper,
  addPaper
} from '@/api/admin/paper'
import {
  queryRepos
} from '@/api/admin/repo'

export default {
  name: 'PaperList',
  directives: { waves },
  data() {
    return {
      // 表格数据
      tableData: [],
      // 记录总数
      recordTotal: 0,
      // 用户数据
      userData: [],
      // 抽屉框显示
      // drawerVisable: false,
      // 查询参数
      queryParam: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        creator: null
      },
      // 当前操作的试卷id
      paperId: null,
      dialogFormVisible: false,
      formType: 0,
      // 表单数据
      form: {
        id: null,
        judgeCount: null,
        multiCount: null,
        name: null,
        qualifyScore: null,
        questionCount: null,
        repoId: null,
        repoName: null,
        sigleCount: null,
        totalScore: null
      },
      rules: {
        repoId: [
          { required: true, message: '请选择题库', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入试卷名', trigger: 'blur' }
        ],
        sigleCount: [
          { required: true, message: '请输入单选题数量', trigger: 'blur' }
        ],
        multiCount: [
          { required: true, message: '请输入多选题数量', trigger: 'blur' }
        ],
        judgeCount: [
          { required: true, message: '请输入判断题数量', trigger: 'blur' }
        ],
        // totalScore: [
        //   { required: true, message: '请输入总分', trigger: 'blur' }
        // ],
        qualifyScore: [
          { required: true, message: '请输入及格分', trigger: 'blur' }
        ]
      },
      repoList: []
    }
  },
  computed: {
    // 获得user信息
    // ...mapGetters(['id', 'name', 'roles', 'avatar']),
    // 通过表单类型计算表单标题
    formTitle() {
      return this.formType === 0 ? '添加试卷' : '修改试卷'
    }
  },
  // 创建后
  created() {
    // 从服务器获取数据表格第一页的信息
    // 默认page=1，size=10
    this.queryPage()
    this.queryReposList()
  },
  methods: {
    // 是否可删除
    selectable(row) {
      if (row.id === 1 || row.id === 2) {
        return false
      }
      return true
    },
    canDelete(row) {
      if (row.id === 1 || row.id === 2) {
        return true
      }
      return false
    },
    // 编辑
    submitForm() {
      if (this.formType === 0) {
        // 添加记录
        addPaper(this.form).then((res) => {
          if (res.status === 200) {
            this.$message.success('添加记录成功')
            this.handleCurrentChange(this.queryParam.pageNum)
          } else {
            this.$message.error('添加记录失败')
          }
          this.dialogFormVisible = false // 关闭对话框
        })
      } else if (this.formType === 1) {
        // 更新记录
        updatePaper(this.form).then((res) => {
          if (res.status === 200) {
            this.$message.success('更新记录成功')
            this.queryPage()
          } else {
            this.$message.error('更新记录失败')
          }
          this.dialogFormVisible = false // 关闭对话框
        })
      }
    },
    // 查询分页
    queryReposList() {
      queryRepos().then((res) => {
        if (res.status === 200) {
          this.repoList = res.data
        }
      })
    },
    // 点击修改记录
    handleUpdate(row) {
      // 表单是修改状态
      this.formType = 1
      // 将行数据置入form
      this.form = {
        id: row.id,
        judgeCount: row.judgeCount,
        multiCount: row.multiCount,
        name: row.name,
        qualifyScore: row.qualifyScore,
        questionCount: row.questionCount,
        repoId: row.repoId,
        repoName: row.repoName,
        sigleCount: row.sigleCount
        // totalScore: row.totalScore
      }
      // 显示表单框
      this.dialogFormVisible = true
    },
    // 点击添加记录
    handleCreate() {
      // 表单是添加状态
      this.formType = 0
      // 将空数据置入form
      this.form = {
        id: null,
        judgeCount: null,
        multiCount: null,
        name: null,
        qualifyScore: null,
        questionCount: null,
        repoId: null,
        repoName: null,
        sigleCount: null,
        totalScore: null
      }
      // 显示表单框
      this.dialogFormVisible = true
    },
    // 查询分页
    queryPage() {
      queryPapersByPage(this.queryParam).then((res) => {
        if (res.status === 200) {
          this.tableData = res.data.rows
          this.recordTotal = res.data.total
        }
      })
    },

    // 分页大小改变监听
    handleSizeChange(curSize) {
      this.queryParam.pageSize = curSize
      this.queryPage()
    },

    // 点击分页监听方法
    handleCurrentChange(curPage) {
      this.queryParam.pageNum = curPage
      this.queryPage()
    },

    // 搜索
    handleFilter() {
      this.queryParam.pageNum = 1
      this.queryPage()
    },

    // 点击显示全部
    handleShowAll() {
      this.queryParam.pageNum = 1
      // 清空
      this.queryParam.name = null
      this.queryParam.creator = null
      this.queryPage()
    },

    // 删除记录
    handleDelete(row, index) {
      this.$confirm('确定要删除该条记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removePaper(row.id).then((res) => {
          if (res.status === 200) {
            this.$message.success('删除记录成功')
            this.tableData.splice(index, 1)
            // 如果删完了，获取上一页
            if (this.tableData.length === 0) {
              this.queryParam.pageNum = this.queryParam.pageNum - 1
              this.handleCurrentChange(this.queryParam.pageNum)
            }
          } else {
            this.$message.error(res.message)
          }
        })
      })
    },

    // 删除一些
    handleDeleteSome() {
      // 获取选中的对象数组
      const items = this.$refs.multipleTable.selection
      if (items.length === 0) {
        this.$message.error('至少选择一条记录')
        return
      }
      this.$confirm('确定要删除这些记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const idList = []
        items.forEach(element => {
          idList.push(element.id)
        })
        const ids = idList.join(',')
        removePapers({ ids }).then((res) => {
          if (res.status === 200) {
            this.$message.success('批量删除记录成功')
            if (this.tableData.length === items.length) {
              // 如果本页内容全部删光了
              // 当前页为上一页
              if (this.queryParam.pageNum !== 0) {
                this.queryParam.pageNum = this.queryParam.pageNum - 1
              }
            }
          } else {
            this.$message.error(res.message)
          }
          // 重载当前页
          this.handleCurrentChange(this.queryParam.pageNum)
        })
      })
    }
  }
}
</script>

<style scoped>
/*1.显示滚动条：当内容超出容器的时候，可以拖动：*/
::v-deep .el-drawer__body {
  overflow: auto;
}
</style>
